<template>

    <div class="animated fadeIn">
        <Icon type="person-add"></Icon>
        <i-button type="error" @click="addUser">添加用户</i-button>
        <br>
        <Table :columns="columns1" :data="data1"></Table>
        <Page :total="totalElements" :page-size="size" :current="page" @on-change="gopage" align="center"></Page>
        <Modal
                v-model="modal1"
                title="编辑用户"
                @on-ok="update"
                @on-cancel="cancel" width="60%">
            <Form ref="editForm" :model="editForm" :rules="ruleCustom" :label-width="80">
                <FormItem label="用户编号" prop="id">
                    <Input type="text" readonly v-model="editForm.id"></Input>
                </FormItem>
                <FormItem label="姓名" prop="name">
                    <Input type="text" v-model="editForm.name"></Input>
                </FormItem>
                <FormItem label="年龄" prop="age">
                    <Input type="text" v-model="editForm.age" number></Input>
                </FormItem>
                <FormItem label="地址" prop="addr">
                    <Input type="text" v-model="editForm.addr"></Input>
                </FormItem>
            </Form>
        </Modal>


        <Modal
                v-model="modal2"
                title="添加用户"
                @on-ok="add"
                @on-cancel="cancel" width="60%">
            <Form ref="addForm" :model="addForm" :rules="ruleCustom" :label-width="80">
                <FormItem label="姓名" prop="name">
                    <Input type="text" v-model="addForm.name"></Input>
                </FormItem>
                <FormItem label="年龄" prop="age">
                    <Input type="text" v-model="addForm.age" number></Input>
                </FormItem>
                <FormItem label="地址" prop="addr">
                    <Input type="text" v-model="addForm.addr"></Input>
                </FormItem>
            </Form>
        </Modal>
    </div>
</template>
<script>
    /* eslint-disable indent,arrow-body-style,object-curly-spacing,object-shorthand */

    import fetch from 'utils/fetch';
    export default {
        data() {
            const validateUser = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入用户名'));
                }
            };
            const validateAddr = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入地址'));
                }
            };
            const validateAge = (rule, value, callback) => {
                if (value === '') {
                    return callback(new Error('年龄不能为空'));
                }
                // 模拟异步验证效果
                setTimeout(() => {
                    if (!Number.isInteger(Number.parseInt(value))) {
                        callback(new Error('请输入整数'));
                    } else {
                        if (value < 18) {
                            callback(new Error('必须年满18！'));
                        } else {
                            callback();
                        }
                    }
                }, 1000);
            };
            return {
                tempIndex: 0, // 临时记录编辑的data1索引
                page: 1,
                size: 2,
                totalPage: 4,
                totalElements: 0,
                columns1: [
                    {
                        title: '姓名',
                        key: 'name'
                    },
                    {
                        title: '年龄',
                        key: 'age'
                    },
                    {
                        title: '地址',
                        key: 'addr'
                    },
                    {
                        title: '操作',
                        key: 'action',
                        align: 'center',
                        render: (h, params) => {
                            return h('div', [
                                h('Button', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        marginRight: '5px'
                                    },
                                    on: {
                                        click: () => {
                                            this.show(params.index)
                                        }
                                    }
                                }, '查看'),
                                h('Button', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        marginRight: '5px'
                                    },
                                    on: {
                                        click: () => {
                                            this.edit(params.index)
                                        }
                                    }
                                }, '编辑'),
                                h('Button', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    on: {
                                        click: () => {
                                            this.remove(params.index)
                                        }
                                    }
                                }, '删除')
                            ]);
                        }
                    }
                ],
                data1: [],
                modal1: false,
                modal2: false,
                editForm: {},
                addForm: {},
                ruleCustom: {
                    name: [
                        {validator: validateUser, trigger: 'blur'}
                    ],
                    addr: [
                        {validator: validateAddr, trigger: 'blur'}
                    ],
                    age: [
                        {validator: validateAge, trigger: 'blur'}
                    ]
                }
            }
        },
        created: function() {
            this.gopage(this.page, this.size);
        },
        methods: {
            addUser() {
                this.modal2 = true;
            },
            add() {
                // 提交数据到服务器
                fetch({
                    url: '/api/user/',
                    method: 'post',
                    data: this.addForm
                }).then(rep => {
                    if (!rep.data === true) {
                        this.$Message.error('服务器更新错误');
                    } else {
                        this.gopage(this.page, this.size);
                    }
                });
            },
            show(index) {
                this.$Modal.info({
                    title: '用户信息',
                    content: `姓名：${this.data1[index].name}<br>年龄：${this.data1[index].age}<br>地址：${this.data1[index].addr}`
                });
            },
            edit(index) {
                this.modal1 = true;
                this.tempIndex = index;
                this.editForm.name = this.data1[index].name;
                this.editForm.age = this.data1[index].age;
                this.editForm.addr = this.data1[index].addr;
                this.editForm.id = this.data1[index].id;
            },
            remove(index) {
                const id = this.data1[index].id;
                // 删除服务器数据
                fetch({
                    url: '/api/user/' + id,
                    method: 'delete'
                }).then(rep => {
                    if (rep.data === true) {
                        // 删除本地数据
                        this.data1.splice(index, 1);
                    } else {
                        this.$Message.error('服务器删除错误');
                    }
                });
            },
            update() {
                this.modal1 = false;
                // 更新本地数据(既然都双向绑定，为什么这句话不能改变表格中的数据？可能是bug吧，所以我又重新请求了一次)
                this.data1[this.tempIndex] = this.editForm;

                const user = this.data1[this.tempIndex];
                // 提交数据到服务器
                fetch({
                    url: '/api/user/',
                    method: 'put',
                    data: user
                }).then(rep => {
                    if (!rep.data === true) {
                        this.$Message.error('服务器更新错误');
                    } else {
                        this.gopage(this.page, this.size);
                    }
                });
            },
            cancel() {
                this.$Message.info('点击了取消');
            },
            gopage(page, size) {
                fetch({
                    url: '/api/user',
                    method: 'get',
                    params: {page, size}
                }).then(rep => {
                    this.data1 = rep.data.content;
                    this.page = page;
                    this.size = rep.data.size;
                    this.totalElements = rep.data.totalElements;
                });
            }
        }
    }
</script>